<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>本地视频播放器（点击视频区域上传）</title>
    <!-- 引入Tailwind CSS -->
    <script src="https://cdn.tailwindcss.com"></script>
    <!-- 引入Font Awesome -->
    <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">
    
    <!-- Tailwind配置 -->
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        primary: '#3B82F6',
                        secondary: '#1E40AF',
                        dark: '#1E293B',
                        light: '#F8FAFC'
                    },
                    fontFamily: {
                        inter: ['Inter', 'system-ui', 'sans-serif'],
                    },
                }
            }
        }
    </script>
    
    <style type="text/tailwindcss">
        @layer utilities {
            .content-auto {
                content-visibility: auto;
            }
            .player-shadow {
                box-shadow: 0 10px 30px -5px rgba(0, 0, 0, 0.2);
            }
            .progress-thumb {
                transform: scale(0);
                transition: transform 0.2s ease;
            }
            .progress-bar:hover .progress-thumb {
                transform: scale(1);
            }
            .subtitles {
                text-shadow: 0 0 2px rgba(0, 0, 0, 0.8);
            }
            .file-input-hidden {
                position: absolute;
                width: 1px;
                height: 1px;
                padding: 0;
                margin: -1px;
                overflow: hidden;
                clip: rect(0, 0, 0, 0);
                border: 0;
            }
            .video-area-cursor {
                cursor: pointer;
            }
            .upload-overlay {
                transition: all 0.3s ease;
                backdrop-filter: blur(2px);
            }
            .upload-overlay:hover {
                background-color: rgba(59, 130, 246, 0.15);
            }
            .control-opacity {
                transition: opacity 0.3s ease;
            }
        }
    </style>
</head>
<body class="bg-gray-100 font-inter min-h-screen flex items-center justify-center p-4">
    <div class="max-w-6xl w-full">
        <!-- 播放器容器（整合上传功能） -->
        <div id="playerContainer" class="bg-dark rounded-xl overflow-hidden player-shadow relative group video-area-cursor">
            <!-- 视频元素 -->
            <video id="videoPlayer" class="w-full aspect-video object-contain bg-black" 
                   poster="https://picsum.photos/1280/720?random=1"
                   preload="metadata">
                您的浏览器不支持HTML5视频播放
            </video>
            
            <!-- 加载指示器 -->
            <div id="loader" class="absolute inset-0 flex items-center justify-center bg-black/50 z-10 hidden">
                <div class="w-16 h-16 border-4 border-primary border-t-transparent rounded-full animate-spin"></div>
            </div>
            
            <!-- 上传提示覆盖层（初始显示，点击/拖放触发上传） -->
            <div id="uploadOverlay" class="absolute inset-0 flex flex-col items-center justify-center z-10 text-white p-6 text-center upload-overlay">
                <i class="fa fa-upload text-6xl mb-4 text-primary/80 transition-transform hover:scale-110"></i>
                <h3 class="text-2xl mb-2">点击或拖拽视频到此处</h3>
                <p class="text-gray-300 max-w-md mb-6">支持MP4、WebM、MOV等常见视频格式</p>
                <span class="inline-block px-4 py-2 bg-primary/20 rounded-full text-sm">
                    <i class="fa fa-file-video-o mr-2"></i>选择本地视频文件
                </span>
            </div>
            
            <!-- 大尺寸播放按钮（视频加载后显示） -->
            <div id="bigPlayButton" class="absolute inset-0 flex items-center justify-center z-10 cursor-pointer hidden">
                <div class="w-20 h-20 rounded-full bg-primary/80 flex items-center justify-center text-white transition-transform hover:scale-110">
                    <i class="fa fa-play text-3xl ml-1"></i>
                </div>
            </div>
            
            <!-- 字幕显示区域 -->
            <div id="subtitlesContainer" class="absolute bottom-24 left-0 right-0 flex justify-center px-4 z-10">
                <div class="subtitles text-white text-lg md:text-xl max-w-3xl text-center"></div>
            </div>
            
            <!-- 播放控制栏 -->
            <div class="absolute bottom-0 left-0 right-0 bg-gradient-to-t from-black/80 to-transparent text-white p-4 z-10 opacity-0 control-opacity">
                <!-- 进度条 -->
                <div class="relative h-1 bg-gray-500 rounded-full mb-4 cursor-pointer progress-bar group" id="progressBar">
                    <div id="progressFilled" class="absolute top-0 left-0 h-full bg-primary rounded-full" style="width: 0%"></div>
                    <div id="progressBuffer" class="absolute top-0 left-0 h-full bg-primary/30 rounded-full" style="width: 0%"></div>
                    <div class="progress-thumb absolute top-1/2 -translate-y-1/2 w-3 h-3 bg-white rounded-full" style="left: 0%"></div>
                </div>
                
                <div class="flex items-center justify-between">
                    <!-- 左侧控制按钮 -->
                    <div class="flex items-center space-x-4">
                        <!-- 播放/暂停 -->
                        <button id="playPauseBtn" class="text-white hover:text-primary transition-colors">
                            <i class="fa fa-play text-xl"></i>
                        </button>
                        
                        <!-- 音量控制 -->
                        <div class="flex items-center space-x-2 group/volume">
                            <button id="muteBtn" class="text-white hover:text-primary transition-colors">
                                <i class="fa fa-volume-up text-xl"></i>
                            </button>
                            <div class="w-24 h-1 bg-gray-500 rounded-full overflow-hidden opacity-0 group-hover/volume:opacity-100 transition-opacity">
                                <div id="volumeBar" class="h-full bg-white rounded-full" style="width: 100%"></div>
                            </div>
                        </div>
                        
                        <!-- 时间显示 -->
                        <div class="text-sm md:text-base">
                            <span id="currentTime">00:00</span>
                            <span class="mx-1">/</span>
                            <span id="duration">00:00</span>
                        </div>
                    </div>
                    
                    <!-- 右侧控制按钮 -->
                    <div class="flex items-center space-x-4">
                        <!-- 字幕选择 -->
                        <div class="relative group/subtitles">
                            <button class="text-white hover:text-primary transition-colors">
                                <i class="fa fa-closed-captioning text-xl"></i>
                            </button>
                            <div id="subtitlesMenu" class="absolute bottom-full right-0 mb-2 bg-dark/90 rounded-lg shadow-lg p-2 hidden group-hover/subtitles:block w-48 z-20">
                                <button class="subtitles-option w-full text-left px-3 py-2 hover:bg-primary/20 rounded text-sm bg-primary/20" data-lang="off">关闭字幕</button>
                                <button class="subtitles-option w-full text-left px-3 py-2 hover:bg-primary/20 rounded text-sm" data-lang="en">英文</button>
                                <button class="subtitles-option w-full text-left px-3 py-2 hover:bg-primary/20 rounded text-sm" data-lang="zh">中文</button>
                            </div>
                        </div>
                        
                        <!-- 播放速度调节 -->
                        <div class="relative group/speed">
                            <button id="speedBtn" class="text-white hover:text-primary transition-colors text-sm md:text-base">
                                1.0x
                            </button>
                            <div id="speedMenu" class="absolute bottom-full right-0 mb-2 bg-dark/90 rounded-lg shadow-lg p-2 hidden group-hover/speed:block z-20">
                                <button class="speed-option w-full text-left px-3 py-2 hover:bg-primary/20 rounded text-sm" data-speed="0.5">0.5x</button>
                                <button class="speed-option w-full text-left px-3 py-2 hover:bg-primary/20 rounded text-sm" data-speed="0.75">0.75x</button>
                                <button class="speed-option w-full text-left px-3 py-2 hover:bg-primary/20 rounded text-sm bg-primary/20" data-speed="1">1.0x</button>
                                <button class="speed-option w-full text-left px-3 py-2 hover:bg-primary/20 rounded text-sm" data-speed="1.25">1.25x</button>
                                <button class="speed-option w-full text-left px-3 py-2 hover:bg-primary/20 rounded text-sm" data-speed="1.5">1.5x</button>
                                <button class="speed-option w-full text-left px-3 py-2 hover:bg-primary/20 rounded text-sm" data-speed="2">2.0x</button>
                            </div>
                        </div>
                        
                        <!-- 画中画模式 -->
                        <button id="pipBtn" class="text-white hover:text-primary transition-colors">
                            <i class="fa fa-clone text-xl"></i>
                        </button>
                        
                        <!-- 全屏切换 -->
                        <button id="fullscreenBtn" class="text-white hover:text-primary transition-colors">
                            <i class="fa fa-expand text-xl"></i>
                        </button>
                    </div>
                </div>
            </div>
            
            <!-- 移除原有的<input type="file">，改用Electron原生对话框 -->
        </div>
        
        <!-- 视频信息显示栏（上传成功后显示） -->
        <div class="mt-4 bg-white rounded-lg p-3 shadow hidden" id="videoInfo">
            <div class="flex flex-col sm:flex-row items-start sm:items-center justify-between gap-2">
                <div class="flex items-center">
                    <i class="fa fa-check-circle text-green-500 mr-2"></i>
                    <span class="text-gray-700">已选择视频：</span>
                    <span id="localFileName" class="font-medium ml-2 truncate max-w-xs sm:max-w-md"></span>
                </div>
                <button id="changeVideoBtn" class="text-primary hover:text-secondary text-sm flex items-center transition-colors">
                    <i class="fa fa-refresh mr-1"></i> 更换视频
                </button>
            </div>
        </div>
    </div>

    <script>
        document.addEventListener('DOMContentLoaded', function() {
            // 1. 获取所有DOM元素
            const video = document.getElementById('videoPlayer');
            const playerContainer = document.getElementById('playerContainer');
            const uploadOverlay = document.getElementById('uploadOverlay');
            const bigPlayButton = document.getElementById('bigPlayButton');
            const loader = document.getElementById('loader');
            const playPauseBtn = document.getElementById('playPauseBtn');
            const progressBar = document.getElementById('progressBar');
            const progressFilled = document.getElementById('progressFilled');
            const progressBuffer = document.getElementById('progressBuffer');
            const progressThumb = document.querySelector('.progress-thumb');
            const currentTimeEl = document.getElementById('currentTime');
            const durationEl = document.getElementById('duration');
            const muteBtn = document.getElementById('muteBtn');
            const volumeBar = document.getElementById('volumeBar');
            const fullscreenBtn = document.getElementById('fullscreenBtn');
            const speedBtn = document.getElementById('speedBtn');
            const speedOptions = document.querySelectorAll('.speed-option');
            const pipBtn = document.getElementById('pipBtn');
            const subtitlesOptions = document.querySelectorAll('.subtitles-option');
            const subtitlesContainer = document.querySelector('.subtitles');
            const videoInfo = document.getElementById('videoInfo');
            const localFileName = document.getElementById('localFileName');
            const changeVideoBtn = document.getElementById('changeVideoBtn');
            const controls = playerContainer.querySelector('.control-opacity');

            // 2. 初始化变量
            const subtitles = { // 内置字幕数据
                en: [
                    {start: 1, end: 4, text: "HTML5 video player supports local files"},
                    {start: 5, end: 8, text: "Click the video area to upload files"},
                    {start: 9, end: 12, text: "Drag and drop is also supported"}
                ],
                zh: [
                    {start: 1, end: 4, text: "HTML5视频播放器支持本地文件"},
                    {start: 5, end: 8, text: "点击视频区域可上传文件"},
                    {start: 9, end: 12, text: "同时支持拖放上传功能"}
                ]
            };
            let currentSubtitles = 'off'; // 当前字幕状态
            let controlsTimeout = null; // 控制栏自动隐藏计时器
            let objectUrl = null; // 本地视频临时URL（拖放上传用）
            let hasVideoLoaded = false; // 视频是否已加载标记

            // 3. 核心工具函数
            // 格式化时间（秒转 MM:SS）
            function formatTime(seconds) {
                if (isNaN(seconds)) return "00:00";
                const minutes = Math.floor(seconds / 60);
                const secs = Math.floor(seconds % 60);
                return `${minutes.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`;
            }

            // 显示控制栏（3秒后自动隐藏）
            function showControls() {
                if (!hasVideoLoaded) return;
                controls.style.opacity = '1';
                clearTimeout(controlsTimeout);
                if (!video.paused) {
                    controlsTimeout = setTimeout(() => {
                        controls.style.opacity = '0';
                    }, 3000);
                }
            }

            // 释放本地视频临时URL（避免内存泄漏）
            function revokeObjectUrl() {
                if (objectUrl) {
                    URL.revokeObjectURL(objectUrl);
                    objectUrl = null;
                }
            }

            // 4. 视频加载核心函数（支持路径/文件两种方式）
            /**
             * 加载视频（通过文件路径，用于双击打开/手动选择）
             * @param {string} filePath - 视频文件绝对路径
             */
            function loadVideoByPath(filePath) {
                if (!filePath) return;
                
                // 显示加载状态
                loader.classList.remove('hidden');
                uploadOverlay.classList.add('hidden');
                videoInfo.classList.add('hidden');
                revokeObjectUrl(); // 释放之前的临时URL

                // Electron中本地视频必须用file://协议前缀
                const videoUrl = new URL(filePath, 'file:///').href;
                video.src = videoUrl;
                video.load();

                // 视频加载成功/失败处理
                video.addEventListener('canplay', onVideoLoaded, { once: true });
                video.addEventListener('error', onVideoLoadError, { once: true });

                // 提取并显示文件名（兼容Windows/macOS路径）
                const fileName = filePath.split(/[\\/]/).pop();
                localFileName.textContent = fileName;
            }

            /**
             * 加载视频（通过File对象，用于拖放上传）
             * @param {File} file - 拖放的视频文件对象
             */
            function loadVideoByFile(file) {
                if (!file || !file.type.startsWith('video/')) {
                    alert('请选择有效的视频文件（支持MP4、WebM等格式）');
                    return;
                }

                // 显示加载状态
                loader.classList.remove('hidden');
                uploadOverlay.classList.add('hidden');
                videoInfo.classList.add('hidden');
                revokeObjectUrl();

                // 创建File对象的临时URL
                objectUrl = URL.createObjectURL(file);
                video.src = objectUrl;
                video.load();

                // 视频加载成功/失败处理
                video.addEventListener('canplay', onVideoLoaded, { once: true });
                video.addEventListener('error', onVideoLoadError, { once: true });

                // 显示文件名
                localFileName.textContent = file.name;
            }

            // 视频加载成功回调
            function onVideoLoaded() {
                loader.classList.add('hidden');
                bigPlayButton.classList.remove('hidden');
                videoInfo.classList.remove('hidden');
                hasVideoLoaded = true;
                durationEl.textContent = formatTime(video.duration);
                showControls(); // 显示控制栏
            }

            // 视频加载失败回调
            function onVideoLoadError() {
                loader.classList.add('hidden');
                uploadOverlay.classList.remove('hidden');
                hasVideoLoaded = false;
                alert('视频加载失败，可能是格式不支持或文件已损坏');
                revokeObjectUrl();
            }

            // 5. 视频播放控制逻辑（保持原有功能不变）
            // 切换播放/暂停
            function togglePlay() {
                if (video.paused || video.ended) {
                    video.play().then(() => {
                        playPauseBtn.innerHTML = '<i class="fa fa-pause text-xl"></i>';
                        bigPlayButton.classList.add('hidden');
                    }).catch(err => {
                        console.error('播放失败:', err);
                        alert('视频播放失败，请检查文件格式是否支持');
                    });
                } else {
                    video.pause();
                    playPauseBtn.innerHTML = '<i class="fa fa-play text-xl"></i>';
                    bigPlayButton.classList.remove('hidden');
                }
            }

            // 更新进度条与时间显示
            function updateProgress() {
                if (isNaN(video.duration) || !hasVideoLoaded) return;
                // 播放进度
                const playPercent = (video.currentTime / video.duration) * 100;
                progressFilled.style.width = `${playPercent}%`;
                progressThumb.style.left = `${playPercent}%`;
                currentTimeEl.textContent = formatTime(video.currentTime);

                // 缓冲进度
                if (video.buffered.length > 0) {
                    const bufferPercent = (video.buffered.end(video.buffered.length - 1) / video.duration) * 100;
                    progressBuffer.style.width = `${bufferPercent}%`;
                }

                // 字幕更新
                updateSubtitles();
            }

            // 更新字幕显示
            function updateSubtitles() {
                if (currentSubtitles === 'off' || !hasVideoLoaded) {
                    subtitlesContainer.textContent = '';
                    return;
                }
                const currentTime = video.currentTime;
                const targetSub = subtitles[currentSubtitles].find(sub => 
                    currentTime >= sub.start && currentTime <= sub.end
                );
                subtitlesContainer.textContent = targetSub ? targetSub.text : '';
            }

            // 音量控制
            function toggleMute() {
                video.muted = !video.muted;
                updateVolumeUI();
            }

            function updateVolumeUI() {
                const volumeLevel = video.volume * 100;
                volumeBar.style.width = video.muted ? '0%' : `${volumeLevel}%`;
                
                if (video.muted || volumeLevel === 0) {
                    muteBtn.innerHTML = '<i class="fa fa-volume-off text-xl"></i>';
                } else if (volumeLevel < 50) {
                    muteBtn.innerHTML = '<i class="fa fa-volume-down text-xl"></i>';
                } else {
                    muteBtn.innerHTML = '<i class="fa fa-volume-up text-xl"></i>';
                }
            }

            function setVolume(percent) {
                video.volume = percent / 100;
                video.muted = percent === 0;
                updateVolumeUI();
            }

            // 进度条跳转
            function seekTo(percent) {
                if (isNaN(video.duration) || !hasVideoLoaded) return;
                video.currentTime = (percent / 100) * video.duration;
            }

            // 全屏切换
            function toggleFullscreen() {
                if (!document.fullscreenElement) {
                    if (playerContainer.requestFullscreen) {
                        playerContainer.requestFullscreen();
                    } else if (playerContainer.webkitRequestFullscreen) {
                        playerContainer.webkitRequestFullscreen();
                    } else if (playerContainer.msRequestFullscreen) {
                        playerContainer.msRequestFullscreen();
                    }
                    fullscreenBtn.innerHTML = '<i class="fa fa-compress text-xl"></i>';
                } else {
                    if (document.exitFullscreen) {
                        document.exitFullscreen();
                    } else if (document.webkitExitFullscreen) {
                        document.webkitExitFullscreen();
                    } else if (document.msExitFullscreen) {
                        document.msExitFullscreen();
                    }
                    fullscreenBtn.innerHTML = '<i class="fa fa-expand text-xl"></i>';
                }
            }

            // 播放速度调节
            function setPlaybackSpeed(speed) {
                video.playbackRate = speed;
                speedBtn.textContent = `${speed}x`;
                speedOptions.forEach(option => {
                    option.classList.toggle('bg-primary/20', parseFloat(option.dataset.speed) === speed);
                });
            }

            // 画中画模式
            function togglePictureInPicture() {
                if (!hasVideoLoaded) return;
                if (document.pictureInPictureElement) {
                    document.exitPictureInPicture();
                } else if (document.pictureInPictureEnabled) {
                    video.requestPictureInPicture().catch(err => {
                        console.error('画中画模式失败:', err);
                        alert('您的浏览器不支持画中画模式');
                    });
                }
            }

            // 字幕切换
            function setSubtitles(lang) {
                currentSubtitles = lang;
                subtitlesOptions.forEach(option => {
                    option.classList.toggle('bg-primary/20', option.dataset.lang === lang);
                });
                updateSubtitles();
            }

            // 6. 交互逻辑（对接Electron IPC）
            // 点击视频区域调用Electron文件选择对话框
            playerContainer.addEventListener('click', function(e) {
                // 仅在未加载视频时触发上传（避免与播放操作冲突）
                if (!hasVideoLoaded && e.target !== playPauseBtn && !e.target.closest('.control-opacity')) {
                    window.electronAPI.openFileDialog().then(filePaths => {
                        if (filePaths.length > 0) {
                            loadVideoByPath(filePaths[0]); // 加载选中的第一个视频
                        }
                    });
                }
            });

            // 更换视频按钮
            changeVideoBtn.addEventListener('click', function() {
                window.electronAPI.openFileDialog().then(filePaths => {
                    if (filePaths.length > 0) {
                        loadVideoByPath(filePaths[0]);
                    }
                });
            });

            // 拖放上传功能（保持原有逻辑）
            function setupDragDrop() {
                ['dragenter', 'dragover', 'dragleave', 'drop'].forEach(eventName => {
                    playerContainer.addEventListener(eventName, preventDefaults, false);
                });

                // 阻止默认拖放行为
                function preventDefaults(e) {
                    e.preventDefault();
                    e.stopPropagation();
                }

                // 拖放进入/悬停时高亮
                ['dragenter', 'dragover'].forEach(eventName => {
                    playerContainer.addEventListener(eventName, function() {
                        if (!hasVideoLoaded) {
                            uploadOverlay.classList.add('bg-primary/20');
                        }
                    }, false);
                });

                // 拖放离开/完成时取消高亮
                ['dragleave', 'drop'].forEach(eventName => {
                    playerContainer.addEventListener(eventName, function() {
                        uploadOverlay.classList.remove('bg-primary/20');
                    }, false);
                });

                // 处理文件拖放
                playerContainer.addEventListener('drop', function(e) {
                    if (!hasVideoLoaded && e.dataTransfer.files.length > 0) {
                        loadVideoByFile(e.dataTransfer.files[0]); // 拖放文件用File对象加载
                    }
                }, false);
            }

            // 7. 监听主进程发送的"自动加载视频"事件（双击打开视频时触发）
            window.electronAPI.onLoadVideo((filePath) => {
                loadVideoByPath(filePath);
            });

            // 8. 其他交互事件绑定（保持原有功能）
            // 大播放按钮
            bigPlayButton.addEventListener('click', togglePlay);

            // 播放/暂停按钮
            playPauseBtn.addEventListener('click', togglePlay);

            // 进度条点击跳转
            progressBar.addEventListener('click', function(e) {
                const rect = progressBar.getBoundingClientRect();
                const percent = ((e.clientX - rect.left) / rect.width) * 100;
                seekTo(percent);
            });

            // 音量调节
            muteBtn.addEventListener('click', toggleMute);
            volumeBar.parentElement.addEventListener('click', function(e) {
                const rect = this.getBoundingClientRect();
                const percent = ((e.clientX - rect.left) / rect.width) * 100;
                setVolume(percent);
            });

            // 全屏按钮
            fullscreenBtn.addEventListener('click', toggleFullscreen);

            // 播放速度选择
            speedOptions.forEach(option => {
                option.addEventListener('click', function() {
                    setPlaybackSpeed(parseFloat(this.dataset.speed));
                });
            });

            // 画中画按钮
            pipBtn.addEventListener('click', togglePictureInPicture);

            // 字幕选择
            subtitlesOptions.forEach(option => {
                option.addEventListener('click', function() {
                    setSubtitles(this.dataset.lang);
                });
            });

            // 视频播放状态监听
            video.addEventListener('timeupdate', updateProgress); // 进度更新
            video.addEventListener('waiting', () => loader.classList.remove('hidden')); // 缓冲中
            video.addEventListener('playing', () => loader.classList.add('hidden')); // 播放中
            video.addEventListener('ended', () => { // 播放结束
                playPauseBtn.innerHTML = '<i class="fa fa-play text-xl"></i>';
                bigPlayButton.classList.remove('hidden');
            });

            // 控制栏显示触发（鼠标移动/播放状态变化）
            video.addEventListener('mousemove', showControls);
            video.addEventListener('play', showControls);
            video.addEventListener('pause', showControls);

            // 全屏状态变化
            document.addEventListener('fullscreenchange', function() {
                if (!document.fullscreenElement) {
                    fullscreenBtn.innerHTML = '<i class="fa fa-expand text-xl"></i>';
                } else {
                    fullscreenBtn.innerHTML = '<i class="fa fa-compress text-xl"></i>';
                }
            });

            // 键盘快捷键
            document.addEventListener('keydown', function(e) {
                if (e.target.tagName === 'INPUT' || e.target.tagName === 'TEXTAREA') return;
                
                switch(e.key.toLowerCase()) {
                    case ' ': // 空格
                    case 'k': // K键
                        togglePlay();
                        e.preventDefault();
                        break;
                    case 'f': // F键
                        toggleFullscreen();
                        e.preventDefault();
                        break;
                    case 'm': // M键
                        toggleMute();
                        e.preventDefault();
                        break;
                    case 'arrowleft': // 左箭头
                        video.currentTime = Math.max(0, video.currentTime - 5);
                        e.preventDefault();
                        break;
                    case 'arrowright': // 右箭头
                        video.currentTime = Math.min(video.duration || 0, video.currentTime + 5);
                        e.preventDefault();
                        break;
                    case 'arrowup': // 上箭头
                        setVolume(Math.min(100, (video.volume * 100) + 5));
                        e.preventDefault();
                        break;
                    case 'arrowdown': // 下箭头
                        setVolume(Math.max(0, (video.volume * 100) - 5));
                        e.preventDefault();
                        break;
                    case 'p': // P键
                        togglePictureInPicture();
                        e.preventDefault();
                        break;
                }
            });

            // 页面卸载前释放资源
            window.addEventListener('beforeunload', revokeObjectUrl);

            // 9. 初始化
            setupDragDrop(); // 初始化拖放功能
            updateVolumeUI(); // 初始化音量UI
            setPlaybackSpeed(1); // 默认播放速度1.0x
        });
    </script>
</body>
</html>